import { Component } from '@angular/core';
import {ViewController,NavController,NavParams,ToastController,LoadingController} from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { StorageService } from "../../providers/StorageService";

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';

import {UserService} from "../../providers/UserService";


import {TabsPage} from '../tabs/tabs';
import {STATUS_FAIL} from "../../providers/Constants";
import {catchError} from "rxjs/operators";


@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class Login {
  loginForm: FormGroup;
  phone: any;
  password:any;
  getPhone:any;//接收注册界面的手机号
  getPassword:any;

  constructor(
    public navCtrl: NavController,
    public viewCtrl:ViewController,
    private formBuilder: FormBuilder,
    public loadingCtrl:LoadingController,
    public toastCtrl  : ToastController,
    private userService:UserService,
    private storageService: StorageService,
    public navParams: NavParams
  ){
    this.loginForm = formBuilder.group ({
      phone:['', Validators.compose([Validators.minLength(4), Validators.required, ])],
      password:['', Validators.compose([Validators.required])]
    })
    this.phone = this.loginForm.controls['phone'];
    this.password = this.loginForm.controls['password'];

    //接收手机号、密码
    this.getPhone = navParams.get('phone');
    this.getPassword = this.navParams.get('password');


  }







  ionViewDidLoad() {
    // console.log('ionViewDidLoad Login');
    console.log("page:"+this.navParams.get("page"));
  }
  //登陆
  login(value){
    let loader = this.loadingCtrl.create({
      content: "正在登陆...",
    });
    loader.present();
    setTimeout(() => {
      this.userService.login(value).then(res => {
        if(res["status"]==STATUS_FAIL){
          this.toastCtrl.create({message:res["msg"], duration: 4500}).present();
          loader.dismiss();
          return;
        }
        loader.dismiss();

        if(this.navParams.get("page")=="SignOrlogin" || this.navParams.get("page")=="SignPage" ){ //判断进入登录的入口

          this.navCtrl.setRoot(TabsPage);

        }else {
          this.viewCtrl.dismiss();
        }

        this.storageService.write('UserInfo', res["data"]);
      });
    }, 2000);


  };

  dismiss(){
    this.viewCtrl.dismiss();
  }
}
